package com.kly.msg.component;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.api.config.annotation.NacosValue;
import com.fqgj.common.utils.HttpUtil;
import com.fqgj.common.utils.StringUtils;
import com.fqgj.exception.common.ApplicationException;
import com.fqgj.log.factory.LogFactory;
import com.fqgj.log.interfaces.Log;
import com.google.common.collect.Maps;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author linqu
 */
@Component
public class ApiClient {
    private static Log logger = LogFactory.getLog(ApiClient.class);


    private final String DATA = "data";
    private final String CODE = "code";
    private final String MSG = "msg";
    private final int SUCCESS_CODE = 0;
    @NacosValue(value = "${msg.api.url}", autoRefreshed = true)
    private String API_URL;

//    private String API_URL="http://localhost:9108";

    private final static String msgPushPath = "/message/single/push";
    private final static String contentType = "application/json; charset=utf-8";
    private final static String accept = "application/json";


    public ApiClient() {
    }

    /**
     * http post请求
     */
    public JSONObject post(JSONObject requestObject) {
        Map<String, String> header = Maps.newHashMap();
        header.put("Content-type", contentType);
        header.put("Accept", accept);
        final String response = HttpUtil.postPageBody(API_URL + msgPushPath, header, requestObject.toJSONString());
        logger.info("CallMessageResult, params:{}, result:{}", requestObject.toJSONString(), response);
        return this.processResponse(requestObject, response);

    }


    private JSONObject parseResponse(JSONObject jsonObject) {
        if (jsonObject.containsKey(DATA)) {
            return jsonObject;
        }
        throw new ApplicationException(jsonObject.getString(MSG));


    }



    JSONObject processResponse(JSONObject requestObject, String response) {
        if (StringUtils.isEmpty(response)) {
            logger.error("InvalidResponseFromServer, requestObject:{}, response:{}", requestObject.toJSONString(), response);
            throw new ApplicationException("Invalid Response from server");
        } else {
            JSONObject responseJson;
            try {
                responseJson = JSONObject.parseObject(response);
            } catch (Exception e) {
                throw new ApplicationException(e.getMessage());
            }
            return this.parseResponse(responseJson);
        }
    }

    private void throwException(int statusCode, JSONObject responseJson) throws ApplicationException {
        if (responseJson.containsKey(MSG)) {
            String code = responseJson.getString(CODE);
            String description = responseJson.getString(MSG);
            throw new ApplicationException(code + ":" + description);
        } else {
            this.throwServerException(statusCode, responseJson.toString());
        }
    }

    private void throwServerException(int statusCode, String responseBody) throws ApplicationException {
        StringBuilder sb = new StringBuilder();
        sb.append("Status Code: ").append(statusCode).append("\n");
        sb.append("Server response: ").append(responseBody);
        throw new ApplicationException(sb.toString());
    }

}